import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/views/Dynamic/DynamicItem.dart';
import 'package:thinking/widget/_.dart';

class TopicIndex extends StatefulWidget {
  final int topicIndexId;
  final String topicIndexName;
  final String isSub;
  TopicIndex({required this.topicIndexId,required this.topicIndexName,required this.isSub,});

  @override
  _TopicIndex createState() => _TopicIndex(topicIndexId: topicIndexId,topicIndexName:Uri.decodeComponent(topicIndexName),isSub:int.parse(isSub)==1?true:false);
}

class _TopicIndex extends State<TopicIndex> {
  int topicIndexId;
  String topicIndexName;
  EasyRefreshController _easyRefreshController = EasyRefreshController();
  _TopicIndex({required this.topicIndexId,required this.topicIndexName,required this.isSub});
  late Tag tag;
  TagPage tagPage = TagPage();
    bool isLoad = false;
  late bool isSub;
  ScrollController _scrollController = ScrollController();
  double _opacity = 0.0;
  bool changeDown =true;
  bool changeUp =false;
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if(_scrollController.offset>45 && changeDown){
        setState(() {
          _opacity =1.0;
          changeDown = false;
          changeUp = true;
        });
      }
      if(_scrollController.offset<45 && changeUp){
        setState(() {
          _opacity =0.0;
          changeDown = true;
          changeUp = false;
        });
      }
    });
    getTagValue();

  }



  Future<void> getTagValue({bool isOnLoad: false}) async {
    Tag res = (await TopicService.topicContent(params: {
      "user_Id": SPreferences().getInt('user_Id'),
      "topic_Id": topicIndexId,
      "newDynamic_Page": tagPage.newDynamicPage,
      "newDynamic_Count": tagPage.newDynamicCount
    }))!;
    if (!isOnLoad) {
      tag = res;
      isSub = tag.isSub!;
    } else {
      if (tagPage.canNewDynamic) {
        tag.setNewDynamicList = [
          ...tag.newDynamicList!,
          ...res.newDynamicList!
        ];
      }
    }
    if (res.newDynamicList!.length < tagPage.newDynamicPage)
      tagPage.setCanNewDynamic = false;
    if (!tagPage.canNewDynamic) {
      BotToast.showText(text: '没有更多动态了哦~');
    }
    isLoad = true;
    setState(() {

    });
  }

  Widget easyRefresh(Widget child) {
    return EasyRefresh(
      child: child,
      scrollController: _scrollController,
      header: BezierCircleHeader(backgroundColor: ColorConfig.ThemeColor),
      footer: BezierBounceFooter(backgroundColor: ColorConfig.ThemeColor),
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _easyRefreshController,
      bottomBouncing: true,
      onRefresh: () async {
        tagPage.setNewDynamicPage = 0;
        tagPage.setCanNewDynamic = true;
        await getTagValue();
        _easyRefreshController.finishRefresh(success: true);
      },
      onLoad: () async {
        if (tagPage.canNewDynamic) {
          tagPage.setNewDynamicPage = tagPage.newDynamicPage + 1;
        }
        await getTagValue(isOnLoad: true);
        _easyRefreshController.finishLoad(success: true);
      },
    );
  }

  Future<void> changeSubTopic() async {
    isSub = !isSub;
    await TopicService.changeSubTopic(params: {
      "user_Id": SPreferences().getInt('user_Id'),
      "topic_Id": topicIndexId,
      "isSub": isSub
    });
    if (isSub) {
      BotToast.showText(text: '订阅成功~');
      tag.setTagSubNum = tag.tagSubNum! + 1;
    } else {
      BotToast.showText(text: '已取消');
      tag.setTagSubNum = tag.tagSubNum! - 1;
    }
    setState(() {});
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Column dynamicListItem(
      {required List<DynamicDataEntity> dynamicList,
      required String titleItem}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Panel(
          top: titleItem == '最新' ? 20 : 0,
          bottom: 10,
          child: Text(
            titleItem,
            style: TextStyle(color: ColorConfig.TextColor, fontSize: 13),
          ),
        ),
        Column(
          children: dynamicList
              .map((e) => Panel(
                      child: Container(
                    decoration: BoxDecoration(
                        color: ColorConfig.WhiteBackColor,
                        borderRadius: BorderRadius.all(Radius.circular(5))),
                    child:
                        DynamicItem(key: ValueKey(e.dynamicId), dynamicData: e),
                  )))
              .toList(),
        )
      ],
    );
  }

  Widget titleData() {
    return Panel(
        top: 10,
        bottom: 0,
        child: ListTile(
          minVerticalPadding: 0,
          contentPadding: EdgeInsets.all(0),
          title: Text(
            '#${tag.tagTitle}#',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          subtitle: RichText(
            text: TextSpan(
              style: TextStyle(fontSize: 13, color: ColorConfig.TextColor),
              children: [
                TextSpan(
                    text: tag.tagSubNum! <= 999
                        ? tag.tagSubNum!.toString()
                        : tag.tagSubNum! >= 10000
                            ? '${tag.tagSubNum! ~/ 10000}w+'
                            : '${tag.tagSubNum! ~/ 1000}k+'),
                TextSpan(text: '订阅'),
                TextSpan(text: '  '),
                TextSpan(
                    text: tag.tagCommentNum! <= 999
                        ? tag.tagCommentNum!.toString()
                        : tag.tagCommentNum! >= 10000
                            ? '${tag.tagCommentNum! ~/ 10000}w+'
                            : '${tag.tagCommentNum! ~/ 1000}k+'),
                TextSpan(text: '讨论'),
              ],
            ),
          ),
        ));
  }
  Stack title(){
    return  Stack(
      children: [
        AnimatedOpacity(
          opacity: _opacity,
          child: Container(
            margin: EdgeInsets.only(
              top: Screen.setHeight(Config.top),
            ),
            color: ColorConfig.LineColor,
            height: Screen.setHeight(85),
            width: Screen.width(context),
            child: Center(
              child: Text(
                topicIndexName,
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold
                ),
              ),
            ),
          ),
          duration: Duration(milliseconds: 350),
        )
        ,
        Container(
          margin: EdgeInsets.only(
            top: Screen.setHeight(Config.top),
          ),
          height: Screen.setHeight(85),
          width: Screen.width(context),
          child: ListTile(
            minVerticalPadding: 0,
            contentPadding: EdgeInsets.all(0),
            leading: IconButton(
              onPressed: () {
                Modular.to.pop();
              },
              icon: Icon(
                Icons.arrow_back,
                color: ColorConfig.BlackObsBackColor,
                size: 20,
              ),
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                TopicButton(
                    isSub: isSub,
                    topic: tag,
                    callBack: () async {
                      await changeSubTopic();
                    }),
                IconButton(
                  onPressed: () {},
                  icon: Icon(
                    Icons.share,
                    color:
                    ColorConfig.BlackObsBackColor,
                    size: 20,
                  ),
                )
              ],
            ),
          ),
        ),

      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return isLoad?Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(55),
          child:title(),
        ),
        backgroundColor: ColorConfig.LineColor,
        body:  Empty(
          child:easyRefresh(

            Container(
              child: ListView(
                shrinkWrap: true,
                physics: BouncingScrollPhysics(),
                children: <Widget>[
                  titleData(),
                  dynamicListItem(
                      dynamicList: tag.hotDynamicList!,
                      titleItem: '热门'),

                  Visibility(child: dynamicListItem(
                      dynamicList: tag.newDynamicList!,
                      titleItem: '最新'),
                    visible: tag.newDynamicList!.length != 0,)
                ],
              ),


            ),

          ),
          isShow: tag.hotDynamicList!.length == 0,
        )

    ):Scaffold(
      body: Loading(),
    );
  }
}
